package com.yywq.service.impl;

import com.yywq.error.BusinessException;
import com.yywq.error.EnumBusinessError;
import com.yywq.mapper.AddressMapper;
import com.yywq.mapper.UserMapper;
import com.yywq.pojo.Address;
import com.yywq.pojo.User;
import com.yywq.pojo.view.UserView;
import com.yywq.service.UserService;
import com.yywq.validator.ValidationResult;
import com.yywq.validator.ValidatorImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 吴磊
 * @program: yywq
 * @create: 2021-03-20 22:24
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ValidatorImpl validator;
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public User login(String telPhone, String password) throws BusinessException {
        User user = userMapper.getUserByTelPhone(telPhone);
        if (user == null) {
            throw new BusinessException(EnumBusinessError.USER_NOT_EXIST);
        }
        String userPassword = user.getPassword();
        //比对用户信息内加密的密码是否和传输进来的密码相匹配
        if (!StringUtils.equals(password, userPassword)) {
            throw new BusinessException(EnumBusinessError.USER_LOGIN_FAIL);
        }
        return user;
    }

    @Override
    public int register(User user) throws BusinessException {
        int i;
        if (user == null) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }

        ValidationResult result = validator.validate(user);
        if (result.isHasErrors()) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR, result.getErrorMsg());
        }

        try {
            i = userMapper.insertUser(user);
        } catch (DuplicateKeyException ex) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR, "手机号已重复注册");
        }
        return i;
    }

    @Override
    public UserView getUserView(String id) {
        if (com.alibaba.druid.util.StringUtils.isEmpty(id)) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }
        UserView userView = new UserView();
        User user = userMapper.getUserById(id);
        if (user == null) {
            throw new BusinessException(EnumBusinessError.USER_NOT_EXIST);
        }
        List<Address> address = addressMapper.getAddressByUid(id);
        BeanUtils.copyProperties(user, userView);
        List<String> addressList = address.stream().map(Address::getAddress).collect(Collectors.toList());
        userView.setAddress(addressList);
        return userView;
    }


}
